/*
 * Copyright 2018 the original author or authors.
 *
 * you can use the file or import project.but Do not take legal responsibility.
 * Only for learning communication.
 *
 * Java compiled version 1.8 or higher
 *
 *
 *
 *
 */

package org.liang.javasource.util;

import java.io.File;
import java.io.IOException;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;


/**
 * TODO 描述信息
 * @author houliang
 * @date 2018年3月5日
 */
public abstract class TemplateUtil {
	private static Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
	
	static{
		try {
			String tempPath = getTemplatePath();
			File templateDir = new File(tempPath);
			cfg.setDirectoryForTemplateLoading(templateDir);
			cfg.setDefaultEncoding("UTF-8");
			cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static Template getTemplate(String templateName) {
		Template temp = null;
		try {
			temp = cfg.getTemplate(templateName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return temp;
	} 


	private static final String TEMP_PATH="template";
	/**
	 * 路径不存在，返回null
	 * @param templateName
	 * @return
	 */
	private static String getTemplatePath() {
		String path = null;
		try {
			path =getClassPath()+TEMP_PATH;
		} catch (Exception e) {
		}
		return path;
	}
	
	private static String getClassPath() {
		return TemplateUtil.class.getClassLoader().getResource("").toString().replace("file:/", "");
	}
	
	public static void main(String[] args) {
		String str = TemplateUtil.class.getClassLoader().getResource("beantempl/javabean.ftl").toString().replace("file:/", "");
		System.out.println(str);
	}
}
